package com.lele.filters;

import com.lele.trans.TransactionManager;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.sql.SQLException;

// 过滤器链
@WebFilter("*.one")
public class Filter_B implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("请求B1");

        try {
            // 事务操作，放在这里是因为，把一次请求和响应 当成一个事务
            TransactionManager.beginTrans(); // 开启事务
            System.out.println("开启事务。。。。");
            filterChain.doFilter(servletRequest,servletResponse); // 放行
            TransactionManager.commit(); // 提交事务
            System.out.println("提交事务。。。。");
        } catch (Exception e) { // 注意从dao层开始，所有异常都要抛出不要处理，不然这里捕获不到
            e.printStackTrace();
            try {
                TransactionManager.rollback(); // 如果出现sql异常则回滚
                System.out.println("回滚事务。。。。");
            } catch (SQLException ex) {
                e.printStackTrace();
            }
        }

        System.out.println("响应B2");
    }

    @Override
    public void destroy() {

    }
}
